<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\Request;
use InvalidArgumentException;

class ActingController extends Controller
{
    public function getActing(Request $request)
    {
        $actingModel=\App\Models\Acting::query()->where('type',$request->input('type'))->where('status',1)->first();
        if(!$actingModel){
            return $this->error('暂无接口');
        }
        $query=$this->generateQuery($actingModel);
        try {
            $rest = $this->sendHttp($query, $actingModel);
            $rest['exp_time']=$actingModel->exp_time;
            return $this->success('请求成功',$rest);
        } catch (Exception $e) {
            throw new InvalidArgumentException('请求失败-'.$e->getMessage());
        }

    }

    private function generateQuery($data)
    {
        if($data->method){//post
            $query = [];
            foreach ($data->parameter as $value){
                $query[$value['name']]=$value['value'];
            }
            return $query;
        }else{//get
            $query = '?';
            foreach ($data->parameter as $value){
                $query .= $value['name'].'='.$value['value'].'&';
            }
            //去掉最后的&
            return substr($query,0,-1);
        }
    }

    /**
     * @throws Exception
     */
    private function sendHttp($query, $data)
    {
        if($data->method){
            try {
                $response = \Illuminate\Support\Facades\Http::post($data->url, $query);
                $data = $response->json();
                if ($response->status() == 200) {
                    return $data;
                } else {
                    throw new Exception($data['message']);
                }
            } catch (\Exception $e) {
                throw new Exception($e->getMessage());
            }
        }else{
            try {
                //取消ssl验证
                $response =\Illuminate\Support\Facades\Http::withOptions(['verify' => false])->get($data->url.$query);
                //验证$response->body()是否为xml,json,array格式,并转换为数组
                if ($this->isXml($response->body())) {
                     $arrayData = json_decode(simplexml_load_string($response->body()), true);
                 } elseif (json_decode($response->body())) {
                     $arrayData = json_decode($response->body(), true);
                 } elseif (is_array($response->body())) {
                     $arrayData = $response->body(); // 已经是数组，无需转换
                 } else {
                     throw new InvalidArgumentException('Unsupported content type');
                 }
                //获取$arrayData多维数组中的指定key值
                $restdata=[];
                if($arrayData['status']!=0){
                    throw new Exception('接口响应失败'.($arrayData['info'] ?? ''));
                }else{
                    foreach ($data->restkey as $key=>$value){
                        $valuedata=$this->getArrayKeyByKey($arrayData,$value['name']);
                        $restdata[$value['name']] = $valuedata[0];
                    }

                    return $restdata;
                }
            } catch (\Exception $e) {
                throw new Exception($e->getMessage());
            }
        }
    }

    private function isXml($data)
    {
        if(@simplexml_load_string($data)){
            return true;
        }else{
            return false;
        }
    }

    private function getArrayKeyByKey($arrayData, $searchKey)
    {
        $result = [];
        foreach ($arrayData as $key => $value) {
            if (is_array($value) || is_object($value)) {
                $result = array_merge($result, $this->getArrayKeyByKey((array)$value, $searchKey));
            } elseif ($searchKey === $key) {
                $result[] = $value;
            }
        }
        return $result;
    }

}
